from logging import getLogger

from zope.interface import Interface, implements
from zope.configuration import config, fields
from zope.schema import TextLine, Bool

from zope.component import getGlobalSiteManager

from meercat.storage.interfaces import IStorage
from meercat.storage.sqlalchemy import SqlAlchemyStorage



log = getLogger('meercat.storage.sqlalchemy')

class ISqlAlchemyStorageSchema(Interface):
    name = TextLine(
        title=u'Name',
        description=u'The name of the storage',
        required=True)
    
    schema = TextLine(
        title=u'Schema',
        description=u'The connection schema for the storage i.e. postgres://user:pass@host/db',
        required=True)
    
    null_pool = Bool(
        title=u'Null Pool',
        description=u'Should the storage use the null pool class (necessary for multi-processing',
        required=False,
        default=False)

def sqlalchemy(context, name, schema, null_pool=False):
    log.debug('Registering sqlalchemy storage: name=%s, schema=%s, null_pool=%s' % (str(name),
                                                                                    str(schema),
                                                                                    str(null_pool)))
    
    kwargs = {'encoding': 'utf-8'}
    
    if null_pool:
        from sqlalchemy.pool import NullPool
        kwargs['poolclass'] = NullPool
            
    getGlobalSiteManager().registerUtility(provided=IStorage, name=name,
                                           component=SqlAlchemyStorage(name,
                                                                       schema,
                                                                       **kwargs))
